# web/scheduler.py
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger

from util.log_util import get_the_logger
logger = get_the_logger(__name__)

# 创建调度器
scheduler = BackgroundScheduler()

# 启动调度器
def start_scheduler():
    if not scheduler.running:
        scheduler.start()
        logger.info("调度器已启动")
        # 打印当前任务列表
        for job in scheduler.get_jobs():
            logger.info(f"已注册任务: {job.name} (ID: {job.id}), 下次执行时间: {job.next_run_time}")
    else:
        logger.info("调度器已在运行中")

# 关闭调度器
def shutdown_scheduler():
    if scheduler.running:
        scheduler.shutdown()
        logger.info("调度器已关闭")



def job_get_fund_history_data():
    """拉取数据后自动执行评估"""
    try:
        # 1. 拉取数据
        logger.info("开始拉取基金数据...")
        from fund.get_history_data import get_fund_history_data
        get_fund_history_data()

        # 2. 执行评估
        logger.info("数据拉取完成，开始执行今日评估...")
        from fund.today import evaluate_today_fund
        evaluate_today_fund(is_today=False)

        logger.info("数据拉取和评估均完成")

    except Exception as e:
        logger.error(f"任务执行失败: {str(e)}", exc_info=True)
        raise e


# 添加定时任务
scheduler.add_job(
    func=job_get_fund_history_data,
    trigger=CronTrigger(hour=6, minute=0, day_of_week='mon-fri'),
    id='get_fund_data',
    name='获取基金历史数据',
    replace_existing=True
)


def job_get_fund_realtime_data():
    """获取基金实时数据并更新评估结果"""
    try:
        # 1. 获取实时数据并保存到CSV
        logger.info("Begin to get fund realtime data...")
        from fund.strategy.realtime import get_all_funds_realtime_and_save
        get_all_funds_realtime_and_save()
        logger.info("End to get fund realtime data")

        # 2. 执行评估更新JSON数据
        logger.info("Begin to evaluate today realtime data...")
        from fund.today import evaluate_today_fund
        evaluate_today_fund()
        logger.info("End to evaluate today realtime data")

    except Exception as e:
        logger.error(f"实时数据任务执行失败: {str(e)}", exc_info=True)
        raise e


# 添加实时数据定时任务（工作日14:50）
scheduler.add_job(
    func=job_get_fund_realtime_data,
    trigger=CronTrigger(hour=14, minute=50, day_of_week='mon-fri'),
    id='get_fund_realtime_data_1',
    name='获取基金实时数据1',
    replace_existing=True
)

# 添加实时数据定时任务（工作日14:55）
scheduler.add_job(
    func=job_get_fund_realtime_data,
    trigger=CronTrigger(hour=14, minute=55, day_of_week='mon-fri'),
    id='get_fund_realtime_data_2',
    name='获取基金实时数据2',
    replace_existing=True
)
